import wx

class PacManGame(wx.Frame):
    def __init__(self):
        super(PacManGame, self).__init__(None, title="吃豆人游戏", size=(400, 400))
        self.panel = wx.Panel(self)
        self.panel.Bind(wx.EVT_PAINT, self.OnPaint)
        self.panel.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown)
        self.timer = wx.Timer(self)
        self.Bind(wx.EVT_TIMER, self.OnTimer, self.timer)

        # 初始化游戏状态
        self.pacman_pos = [10, 10]  # 吃豆人初始位置
        self.pacman_dir = (0, 0)    # 吃豆人移动方向
        self.dots = [(x, y) for x in range(20, 380, 20) for y in range(20, 380, 20)]  # 豆子位置
        self.score = 0              # 得分

        self.timer.Start(100)  # 每 100 毫秒更新一次游戏状态
        self.Centre()
        self.Show()

    def OnPaint(self, event):
        dc = wx.PaintDC(self.panel)
        dc.Clear()

        # 绘制吃豆人
        dc.SetBrush(wx.Brush(wx.Colour(255, 255, 0)))  # 黄色
        dc.DrawCircle(self.pacman_pos[0], self.pacman_pos[1], 10)

        # 绘制豆子
        dc.SetBrush(wx.Brush(wx.Colour(255, 0, 0)))  # 红色
        for dot in self.dots:
            dc.DrawCircle(dot[0], dot[1], 5)

        # 显示得分
        dc.DrawText(f"得分: {self.score}", 10, 360)

    def OnKeyDown(self, event):
        keycode = event.GetKeyCode()
        if keycode == wx.WXK_LEFT:
            self.pacman_dir = (-10, 0)
        elif keycode == wx.WXK_RIGHT:
            self.pacman_dir = (10, 0)
        elif keycode == wx.WXK_UP:
            self.pacman_dir = (0, -10)
        elif keycode == wx.WXK_DOWN:
            self.pacman_dir = (0, 10)

    def OnTimer(self, event):
        # 更新吃豆人位置
        self.pacman_pos[0] += self.pacman_dir[0]
        self.pacman_pos[1] += self.pacman_dir[1]

        # 边界检测
        if self.pacman_pos[0] < 10:
            self.pacman_pos[0] = 10
        if self.pacman_pos[0] > 390:
            self.pacman_pos[0] = 390
        if self.pacman_pos[1] < 10:
            self.pacman_pos[1] = 10
        if self.pacman_pos[1] > 390:
            self.pacman_pos[1] = 390

        # 检测吃豆人与豆子的碰撞
        for dot in self.dots[:]:
            if abs(self.pacman_pos[0] - dot[0]) < 15 and abs(self.pacman_pos[1] - dot[1]) < 15:
                self.dots.remove(dot)
                self.score += 1

        # 刷新画面
        self.panel.Refresh()

if __name__ == "__main__":
    app = wx.App(False)
    frame = PacManGame()
    app.MainLoop()
